import numpy as np
import time
from datetime import datetime
import re

class SignalGateway:
    """
    智能信号网关：处理多模态输入适配和路由
    实现跨模态习惯融合
    """
    def __init__(self, quantum_filter):
        self.quantum_filter = quantum_filter
        
        # 输入适配器
        self.adapters = {
            'text': TextAdapter(),
            'voice': VoiceAdapter(),
            'sensor': SensorAdapter()
        }
        
        # 信号处理统计
        self.stats = {
            'total_signals': 0,
            'signal_types': {},
            'processing_time': {},
            'routing_decisions': {},
            'filter_usage': 0,
            'avg_feature_dim': []
        }
        
        # 信号路由规则
        self.routing_rules = {
            'high_priority': {
                'threshold': 0.8,
                'destination': 'learning_engine'
            },
            'medium_priority': {
                'threshold': 0.5,
                'destination': 'memory_pool'
            },
            'low_priority': {
                'threshold': 0.0,
                'destination': 'archive'
            }
        }
        
        # 跨模态特征映射
        self.cross_modal_mapping = {
            'text': {
                'formality': 0,
                'detail_request': 1,
                'emotion': 2,
                'question_count': 3,
                'response_time': 4
            },
            'voice': {
                'speech_rate': 0,
                'pitch_variation': 1,
                'volume': 2,
                'pauses': 3,
                'emotion': 2  # 与文本共享情感维度
            },
            'sensor': {
                'interaction_speed': 4,  # 与文本共享响应时间维度
                'pressure': 5,
                'gesture_complexity': 6,
                'interaction_frequency': 7
            }
        }
        
        # 总特征维度
        self.total_feature_dim = 8

    def _get_priority(self, signal_features, signal_type, context):
        """确定信号优先级"""
        # 基于信号特征、类型和上下文计算优先级
        # 简化实现：使用特征向量的范数作为基础
        base_priority = np.linalg.norm(signal_features) / np.sqrt(len(signal_features))
        
        # 根据信号类型调整
        type_factor = {
            'text': 1.0,
            'voice': 1.2,  # 语音信号优先级稍高
            'sensor': 0.8   # 传感器信号优先级稍低
        }.get(signal_type, 1.0)
        
        # 根据上下文调整
        context_factor = {
            'work': 1.2,   # 工作情境优先级高
            'casual': 0.9, # 休闲情境优先级中等
            'learning': 1.1 # 学习情境优先级较高
        }.get(context, 1.0)
        
        # 计算最终优先级
        priority = base_priority * type_factor * context_factor
        return np.clip(priority, 0.0, 1.0)
    
    def _determine_routing(self, priority):
        """基于优先级确定路由目的地"""
        if priority >= self.routing_rules['high_priority']['threshold']:
            return self.routing_rules['high_priority']['destination']
        elif priority >= self.routing_rules['medium_priority']['threshold']:
            return self.routing_rules['medium_priority']['destination']
        else:
            return self.routing_rules['low_priority']['destination']
    
    def _map_to_common_features(self, modality_features, signal_type):
        """将模态特定特征映射到通用特征空间"""
        common_features = np.zeros(self.total_feature_dim)
        
        # 获取该模态的映射规则
        mapping = self.cross_modal_mapping.get(signal_type, {})
        
        # 映射特征
        for feature_name, feature_value in modality_features.items():
            if feature_name in mapping:
                idx = mapping[feature_name]
                common_features[idx] = feature_value
        
        return common_features
    
    def process_signal(self, raw_input, signal_type, context):
        """
        处理信号：适配、转换、滤波和路由
        实现跨模态习惯融合
        """
        start_time = time.time()
        
        # 验证信号类型
        if signal_type not in self.adapters:
            raise ValueError(f"不支持的信号类型: {signal_type}")
        
        # 使用相应的适配器处理原始输入
        adapter = self.adapters[signal_type]
        modality_features = adapter.process(raw_input)
        
        # 映射到通用特征空间
        common_features = self._map_to_common_features(modality_features, signal_type)
        
        # 应用量子滤波
        filtered_features = self.quantum_filter.filter(common_features, context)
        
        # 计算信号优先级
        priority = self._get_priority(filtered_features, signal_type, context)
        
        # 确定路由
        routing_destination = self._determine_routing(priority)
        
        # 记录处理时间
        processing_time = time.time() - start_time
        
        # 更新统计信息
        self.stats['total_signals'] += 1
        self.stats['signal_types'][signal_type] = self.stats['signal_types'].get(signal_type, 0) + 1
        self.stats['processing_time'][signal_type] = self.stats['processing_time'].get(signal_type, []) + [processing_time]
        self.stats['routing_decisions'][routing_destination] = self.stats['routing_decisions'].get(routing_destination, 0) + 1
        self.stats['filter_usage'] += 1
        self.stats['avg_feature_dim'].append(len(filtered_features))
        
        # 返回处理结果
        return {
            'raw_input': raw_input,
            'signal_type': signal_type,
            'context': context,
            'modality_features': modality_features,
            'features': filtered_features,
            'priority': priority,
            'routing': routing_destination,
            'timestamp': datetime.now().timestamp(),
            'processing_time': processing_time
        }
    
    def get_routing_stats(self):
        """返回路由和信号处理统计信息"""
        # 计算平均处理时间
        avg_processing = {}
        for signal_type, times in self.stats['processing_time'].items():
            avg_processing[signal_type] = np.mean(times) if times else 0
        
        # 计算信号类型分布
        type_distribution = {}
        total = self.stats['total_signals']
        for signal_type, count in self.stats['signal_types'].items():
            type_distribution[signal_type] = count / total if total > 0 else 0
        
        # 计算路由分布
        routing_distribution = {}
        for dest, count in self.stats['routing_decisions'].items():
            routing_distribution[dest] = count / total if total > 0 else 0
        
        return {
            'total_signals': self.stats['total_signals'],
            'signal_types': self.stats['signal_types'],
            'type_distribution': type_distribution,
            'avg_processing_time': avg_processing,
            'routing_decisions': self.stats['routing_decisions'],
            'routing_distribution': routing_distribution,
            'avg_feature_dim': np.mean(self.stats['avg_feature_dim']) if self.stats['avg_feature_dim'] else 0
        }


class TextAdapter:
    """文本输入适配器"""
    def __init__(self):
        # 文本特征提取参数
        self.formality_keywords = {
            'formal': ['请', '您好', '感谢', '麻烦', '请问'],
            'casual': ['嘿', '哦', '啊', '呢', '啦', '哈']
        }
        self.detail_keywords = {
            'high': ['详细', '具体', '如何', '步骤', '解释'],
            'low': ['简', '短', '快', '概要', '总之']
        }
        self.emotion_keywords = {
            'positive': ['好', '棒', '不错', '优秀', '感谢'],
            'negative': ['不', '错', '糟糕', '问题', '麻烦']
        }
        self.emoji_pattern = re.compile(r'[\U0001F600-\U0001F64F\U0001F300-\U0001F5FF\U0001F680-\U0001F6FF\U0001F1E0-\U0001F1FF]')
    
    def _analyze_formality(self, text):
        """分析文本正式程度 (0-1)"""
        formal_count = sum(text.count(word) for word in self.formality_keywords['formal'])
        casual_count = sum(text.count(word) for word in self.formality_keywords['casual'])
        total = formal_count + casual_count
        
        if total == 0:
            return 0.5  # 中性
        
        return formal_count / total
    
    def _analyze_detail_request(self, text):
        """分析对详细程度的需求 (0-1)"""
        high_count = sum(text.count(word) for word in self.detail_keywords['high'])
        low_count = sum(text.count(word) for word in self.detail_keywords['low'])
        total = high_count + low_count
        
        if total == 0:
            return 0.5  # 中性
        
        return high_count / total
    
    def _analyze_emotion(self, text):
        """分析情感倾向 (0-1, 0为负面，1为正面)"""
        positive_count = sum(text.count(word) for word in self.emotion_keywords['positive'])
        negative_count = sum(text.count(word) for word in self.emotion_keywords['negative'])
        emoji_count = len(self.emoji_pattern.findall(text))
        
        # 表情符号倾向于增加正面情感
        positive_count += emoji_count * 0.5
        
        total = positive_count + negative_count
        
        if total == 0:
            return 0.5  # 中性
        
        return positive_count / total
    
    def _count_questions(self, text):
        """计算问题数量"""
        return text.count('?')
    
    def process(self, text):
        """处理文本输入，提取特征"""
        # 基本预处理
        text = text.strip().lower()
        if not text:
            return {}
        
        # 提取文本特征
        return {
            'formality': self._analyze_formality(text),
            'detail_request': self._analyze_detail_request(text),
            'emotion': self._analyze_emotion(text),
            'question_count': min(self._count_questions(text) / 5, 1.0),  # 归一化到0-1
            'response_time': np.random.normal(0.5, 0.2)  # 模拟响应时间，实际中应从用户行为获取
        }


class VoiceAdapter:
    """语音输入适配器（模拟实现）"""
    def __init__(self):
        # 语音特征提取参数
        pass
    
    def _simulate_speech_rate(self, text):
        """模拟语速特征 (0-1)"""
        # 简单模拟：文本越长语速倾向于越快
        return min(len(text) / 100, 1.0)
    
    def _simulate_pitch_variation(self, text):
        """模拟音调变化 (0-1)"""
        # 简单模拟：问号和感叹号多的文本音调变化大
        emotion_marks = text.count('?') + text.count('!')
        return min(emotion_marks / 5, 1.0)
    
    def _simulate_volume(self, text):
        """模拟音量 (0-1)"""
        # 简单模拟：大写字母多的文本音量大
        uppercase_count = sum(1 for c in text if c.isupper())
        return min(uppercase_count / len(text) if text else 0, 1.0)
    
    def _simulate_pauses(self, text):
        """模拟停顿次数 (0-1)"""
        # 简单模拟：逗号和句号多的文本停顿多
        pause_marks = text.count(',') + text.count('.')
        return min(pause_marks / 10, 1.0)
    
    def _simulate_emotion(self, text):
        """模拟情感倾向 (0-1)"""
        # 简单模拟：感叹号多的文本情感更积极
        exclamation_count = text.count('!')
        question_count = text.count('?')
        total = exclamation_count + question_count
        
        if total == 0:
            return 0.5
        
        return exclamation_count / total
    
    def process(self, voice_description):
        """处理语音输入，提取特征（模拟实现）"""
        # 在实际应用中，这里会调用语音处理API
        # 此处使用语音描述文本进行模拟
        
        return {
            'speech_rate': self._simulate_speech_rate(voice_description),
            'pitch_variation': self._simulate_pitch_variation(voice_description),
            'volume': self._simulate_volume(voice_description),
            'pauses': self._simulate_pauses(voice_description),
            'emotion': self._simulate_emotion(voice_description)
        }


class SensorAdapter:
    """传感器输入适配器（模拟实现）"""
    def __init__(self):
        # 传感器特征提取参数
        pass
    
    def process(self, sensor_data):
        """处理传感器输入，提取特征（模拟实现）"""
        # 在实际应用中，这里会处理来自设备的传感器数据
        # 如触摸位置、压力、运动等
        
        # 简单模拟传感器数据
        return {
            'interaction_speed': np.random.normal(0.5, 0.2),
            'pressure': np.random.normal(0.5, 0.2),
            'gesture_complexity': np.random.normal(0.3, 0.2),
            'interaction_frequency': np.random.normal(0.4, 0.2)
        }
    